<template>
  <div v-if="showListen">
    <div ref="wavesurfer" :id="wavesurferId"></div>
    <p v-show="!playShow && showNoUse" class="nouse-audio">录音正在生成，请尝试重新打开这条记录获取录音，若通话未产生通话内容则无法获取录音。</p>
    <div class="wave-detail-box" v-show="playShow">
      <i class="V7_iconfont radio-span" :class="isplay?'V7_iconV7tubiao_bofang-103':'V7_iconV7tubiao_zanting'" @click="playOrPause"></i>
      <a v-if="showDowload" :href="srcUrl" target="_blank"  download><i class="radio-span download-icon V7_iconfont V7_iconV7tubiao_xiazai"></i></a>
      <span class="audio-time">{{timeStr}}</span>
    </div>
  </div>
</template>
<script>
import { getCallTimeLength } from '@utils/common'
import WaveSurfer from 'wavesurfer.js'
let clearInter
const timeNumber = 1000
export default {
  name: 'wavesurfer',
  props: {
    srcUrl: { type: String, default: '' },
    isAutoPlay: { type: Boolean, default: false },
    showListen: { type: Boolean, default: false },
    showDowload: { type: Boolean, default: false },
    wavesurferId: { type: String, default: 'wavesurfer' }
  },
  data () {
    return {
      showNoUse: true,
      wavesurfer: {},
      isplay: true,
      timeStr: '00:00:00/00:00:00',
      currentTime: 0,
      allTime: 0,
      isActivated: false,
      playShow: true
    }
  },
  mounted () {
    this.changeMave()
  },
  methods: {
    getLastTime (time1, time2) {
      return getCallTimeLength(time1) + '/' + getCallTimeLength(time2)
    },
    pauseAudio (flag) {
      this.wavesurfer.pause()
      this.isplay = true
    },
    playOrPause () {
      this.wavesurfer.playPause()
      this.isplay = !this.isplay
      if (this.isActivated) { // 组件再次激活时，重新激活定时器
        this.setInterValTimer()
      }
    },
    closeDial () {
      const pane = document.getElementById(this.wavesurferId)
      if (pane) {
        pane.innerHTML = ''
      }
      if (this.wavesurfer && this.wavesurfer.container) { // 解决第一次加载没有实体，直接调用方法报错导致绘图失败
        this.wavesurfer.destroy()// 删除事件、元素并断开WebAudio节点。
      }
    },
    setInterValTimer () { // 启动定时器
      const self = this
      clearInter = setInterval(() => {
        console.log('setInterValTimer====')
        self.currentTime = Math.round(self.wavesurfer.getCurrentTime() || 0)
        self.timeStr = self.getLastTime(self.currentTime, self.allTime)
      }, timeNumber)
    },
    changeMave () {
      if (this.srcUrl) {
        const pane = document.getElementById(this.wavesurferId)
        if (!this.wavesurferId || !pane) {
          return false
        }
        const option = {
          container: document.getElementById(this.wavesurferId),
          waveColor: '#878787',
          progressColor: '#008CEE',
          cursorColor: '#008CEE',
          splitChannels: true,
          hideScrollbar: true,
          maxCanvasWidth: 500,
          height: 60,
          barHeight: 1,
          // barWidth: 4, // 此配置是波纹柱状显示
          // barGap: 3, // 此配置是结合barWidth使用的，设置柱子间的间距
          pixelRatio: 1,
          backend: 'MediaElement'
        }
        const self = this
        this.wavesurfer = new WaveSurfer(option)
        this.wavesurfer.init()
        this.wavesurfer.load(`${this.srcUrl}?random=${Math.random()}`)
        // 为啥要加Math.random? => 腾讯云的cos 跨域配置有问题，已配置*，但还是会有部分录音加载跨域，故暂时前台加上随机数，每次加载最新的，不缓存
        this.wavesurfer.on('ready', () => {
          this.setInterValTimer() // 启动定时器
          const timer = self.wavesurfer.getDuration()
          self.allTime = timer || 0
          self.playShow = true
          self.showNoUse = true
          self.isplay = true
          if (self.isAutoPlay) { // 是否自动播放
            self.wavesurfer.play()
            self.isplay = false
          } else {
            self.wavesurfer.pause()
            self.isplay = true
          }
        })
        this.wavesurfer.on('error', () => { // 录音加载失败时，就销毁绘图 && 提示无效录音 && 隐藏播放按钮
          self.closeDial()
          self.playShow = false
          console.log('======加载录音失败哒======')
        })
        this.wavesurfer.on('finish', () => { // 录音播放完毕时
          console.log('======录音播放完毕啦======')
          self.isplay = true
        })
      }
    }
  },
  watch: {
    srcUrl (newUrl) {
      this.closeDial() // 更换url的时候先清空原来的，再重新画波纹
      this.currentTime = 0
      this.allTime = 0
      clearInterval(clearInter) // 切换的时候先清除之前的定时器，否则会累加
      this.changeMave()
    }
  },
  activated () { // keep-alive 组件激活时调用时
    this.isActivated = true // 从别的模块再切回来，isActivated用于手动点击播放，再次启动定时器
  },
  deactivated () { // 组件暂停使用时，重置状态
    this.isplay = true
    this.isActivated = false
    clearInterval(clearInter) // 去别的模块，组件暂停使用时，去除定时器
  },
  beforeDestroy () {
    this.closeDial() // 组件被销毁的时候，把音频也销毁
    clearInterval(clearInter) // 销毁的时候去除定时器
  }
}
</script>
<style lang="stylus" scoped>
  .wave-detail-box
    margin-top 16px
    span
     display inline-block
     padding-top 3px
     line-height 16px
  .nouse-audio
    line-height 36px
  .radio-span
    cursor pointer
    color $c-main
    width 24px
    height 24px
    line-height 24px
    display inline-block
    background #fff
    margin-right 10px
    box-shadow 0px 1px 3px 0px rgba(216, 222, 230, 0.9)
    border-radius 50%
    font-size 12px
    text-align center
    vertical-align middle
  .audio-time
    width 110px
</style>
